package com.rc.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.rc.SplashScreen.SplashScreenActivity;
import com.rc.activity.dao.tbl_Profile;
import com.rc.activity.provider.Contract;
import com.rc.custom.DotsProgressBar;
import com.rc.model.Model;
import com.rc.model.TaskType;
import com.rc.object.BaseObject;
import com.rc.object.UserObj;
import com.rc.util.Const;
import com.rc.util.Util;
import com.telpoo.frame.model.TaskParams;
import com.telpoo.frame.ui.BaseActivity;
import com.telpoo.frame.utils.Utils;

public class Login extends BaseActivity implements OnClickListener {

	private EditText txtEmail, txtPassword;
	private TextView txtForgot_Pass, txtSignUp;
	private LinearLayout llContent;
	private Button btLogin;
	private TaskParams params;
	private Model mModel;
	private Long mUserID;

	public static void callIntent(Activity ct) {
		Intent it = new Intent(ct, Login.class);
		it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		it.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		ct.startActivity(it);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.main_login);
		// register
		llContent = (LinearLayout) findViewById(R.id.llContent);
		txtEmail = (EditText) findViewById(R.id.txtEmail);
		txtPassword = (EditText) findViewById(R.id.txtPassWord);
		txtForgot_Pass = (TextView) findViewById(R.id.txtForgotPass);
		btLogin = (Button) findViewById(R.id.btLogin);
		txtSignUp = (TextView) findViewById(R.id.txtSignUp);

		// Funtion
		// this.registerReceiver(Util.mConnReceiver, new IntentFilter(
		// ConnectivityManager.CONNECTIVITY_ACTION));
		txtSignUp.setOnClickListener(this);
		btLogin.setOnClickListener(this);
		txtForgot_Pass.setOnClickListener(this);

		txtEmail.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				Util.setVisiable(txtEmail);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		txtPassword.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				Util.setVisiable(txtPassword);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		txtPassword.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					login();
				}
				return false;
			}
		});
	}

	private void login() {
		Util.HidenKeyBoard(Login.this);
		Utils.hideKeyboard(Login.this, txtPassword);
		Utils.hideKeyboard(Login.this, txtEmail);
		if (validateEditText()) {
			String email = txtEmail.getText().toString();
			email = email.toLowerCase();
			String[] url = { email, txtPassword.getText().toString() };
			// String[] url = { "andrewqsoft@gmail.com", "123456" };
			params = new TaskParams(url);
			mModel = new Model(model, TaskType.TASK_LOGIN, null,
					getBaseContext());
			if (Util.isNetworkActivated(Login.this)) {
				((RelativeLayout) findViewById(R.id.rlContent))
						.setVisibility(View.GONE);
				((DotsProgressBar) findViewById(R.id.progress))
						.setVisibility(View.VISIBLE);
				model.exeTask(params, mModel);
			} else {
				showToast(getString(R.string.no_connection));
			}

		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btLogin:
			login();
			break;
		case R.id.txtSignUp:
			SignUp.callIntent(Login.this);
			break;
		case R.id.txtForgotPass:
			ForgotPass.callIntent(Login.this);
			break;
		default:
			break;
		}
	}

	private boolean validateEditText() {
		if (!Util.validateText(txtEmail)) {
			Util.setError(txtEmail, getString(R.string.input_email));
		} else if (!Util.validateEmail(txtEmail)) {
			Util.setError(txtEmail, getString(R.string.invalid_email));
		} else if (!Util.validateText(txtPassword)) {
			Util.setError(txtPassword, getString(R.string.input_pass));
		} else if (!Util.validateLeng(txtPassword)) {
			Util.setError(txtPassword, getString(R.string.invalid_pass));
		} else {
			return true;
		}
		return false;

	}

	@SuppressWarnings("unchecked")
	@Override
	public void onSuccess(int taskType, ArrayList<?> list, String msg) {
		// TODO Auto-generated method stub
		switch (taskType) {
		case TaskType.TASK_LOGIN:
			ArrayList<BaseObject> arrBaseObjects = (ArrayList<BaseObject>) list;
			for (int i = 0; i < arrBaseObjects.size(); i++) {
				UserObj user = new UserObj();

				// Insert table User
				mUserID = arrBaseObjects.get(i).getParamLong(UserObj.USER_ID);
				user.setUserID(mUserID);
				user.setUsername(arrBaseObjects.get(i).getParam(UserObj.NAME));
				user.setEmail(arrBaseObjects.get(i).getParam(UserObj.EMAIL));
				user.setPassword(arrBaseObjects.get(i).getParam(
						UserObj.PASSWORD));
				user.setIsDefault("");
				user.setToken(arrBaseObjects.get(i).getParam(UserObj.TOKEN));
				Const.AUTHENKEY = arrBaseObjects.get(i).getParam(UserObj.TOKEN);

				this.getContentResolver().insert(Contract.CONTENT_URI_USER,
						user.getContentValues());
				// Insert Table Profile
				tbl_Profile mProfile = new tbl_Profile();
				mProfile.setUserID(mUserID);
				mProfile.setFirstName(arrBaseObjects.get(i).getParam(
						UserObj.FIRST_NAME));
				mProfile.setLastName(arrBaseObjects.get(i).getParam(
						UserObj.LAST_NAME));
				if (arrBaseObjects.get(i).getParamInt(UserObj.GENDER) == 1) {
					mProfile.setGender(true);
				} else {
					mProfile.setGender(false);
				}
				mProfile.setBirthdate(arrBaseObjects.get(i).getParam(
						UserObj.BIRTHDATE));
				mProfile.setMaritalStatus(arrBaseObjects.get(i).getParam(
						UserObj.MARITAL_STATUS));
				mProfile.setProfession(arrBaseObjects.get(i).getParam(
						UserObj.PROFESSION));
				mProfile.setCompanyName(arrBaseObjects.get(i).getParam(
						UserObj.COMPANY_NAME));
				mProfile.setAddressFirst(arrBaseObjects.get(i).getParam(
						UserObj.ADDRESS_FIRST));
				mProfile.setMobile(arrBaseObjects.get(i).getParam(
						UserObj.MOBILE));
				this.getContentResolver().insert(Contract.CONTENT_URI_PROFILE,
						mProfile.getContentValues());
			}
			// lấy toàn bộ merchant sau khi lấy được tổng số merchant.

			callAsynCallServiceCategory();
			break;
		case TaskType.TASK_GET_CATEGORYS:
			// get 30 report from server
			callAsynCallServiceReport("50", "1");
			break;

		case TaskType.TASK_GET_REPORT:
			// get trip by report id
			callAsynCallServiceTrip();
			break;
		case TaskType.TASK_GET_TRIP:
			// get trip free
			callAsynCallServiceTripFree();
			break;
		case TaskType.TASK_GET_TRIP_FREE:
			// get receipt by trip
			callAsynCallServiceReceipt();
			break;
		case TaskType.TASK_GET_RECEIPT:
			// get receipt by trip
			callAsynCallServiceReceiptFree();
			break;
		case TaskType.TASK_GET_RECEIPT_FREE:
			callAsynCallServiceMerchant();
			break;
		case TaskType.TASK_GET_MERCHANT:
			callAsynCallServiceItems();
			break;
		case TaskType.TASK_GET_ITEMS:
			callAsynCallServiceTripItems();
			break;
		case TaskType.TASK_GET_TRIP_ITEMS:
			callAsynCallServiceSettings();
			break;
		case TaskType.TASK_SETTINGS:
			callAsynCallServiceItemPeding();
			break;
		case TaskType.TASK_GET_ITEM_PENDING:
			callAsynCallServiceTripItemPeding();
			break;
		case TaskType.TASK_GET_TRIPITEM_PENDING:
			SplashScreenActivity.callIntent(Login.this);
			break;
		default:
			break;
		}
		super.onSuccess(taskType, list, msg);
	}

	@Override
	public void onFail(int taskType, String msg) {
		switch (taskType) {
		case TaskType.TASK_LOGIN:
			showToast(msg);
			break;
		default:
			showToast(getString(R.string.fail_to_load_data_please_try_again_later));
			break;
		}
		downloadfail();
		super.onFail(taskType, msg);
	}

	@Override
	public void onBackPressed() {

		if (((RelativeLayout) findViewById(R.id.rlContent)).getVisibility() == View.VISIBLE) {
			super.onBackPressed();
			Intent intent = new Intent(Login.this,
					SplashScreenActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("EXIT", true);
			startActivity(intent);
		} else {
			return;
		}
	}

	private void downloadfail() {
		Util.logOut(Login.this);
		SplashScreenActivity.callIntent(Login.this);
	}

	/*
	 * public File getBackupDatabaseFile() { File dir = new
	 * File(Environment.getExternalStorageDirectory() .getAbsolutePath() +
	 * "/backup"); if (!dir.exists()) { dir.mkdirs(); } return new File(dir,
	 * "rci-db"); }
	 * 
	 * public void copy(File src, File dst) throws IOException { InputStream in
	 * = new FileInputStream(src); OutputStream out = new FileOutputStream(dst);
	 * 
	 * // Transfer bytes from in to out byte[] buf = new byte[1024]; int len;
	 * while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close();
	 * out.close(); }
	 *//**
	 * to backup databases from, to.
	 */
	/*
	 * public final boolean backupDatabase() { File from =
	 * getDatabasePath("rci-db");
	 * 
	 * File to = this.getBackupDatabaseFile(); try { copy(from, to); return
	 * true; } catch (IOException e) { // TODO Auto-generated catch block
	 * Log.e(TAG, "Error backuping up database: " + e.getMessage(), e); } return
	 * false; }
	 * 
	 * private String TAG = "DashBoardScreen";
	 *//**
	 * copy file from src to dest
	 * 
	 * @throws IOException
	 */
	/*
	 * public void copyFile(File src, File dst) throws IOException {
	 * FileInputStream in = new FileInputStream(src); FileOutputStream out = new
	 * FileOutputStream(dst); FileChannel fromChannel = null, toChannel = null;
	 * 
	 * try { fromChannel = in.getChannel(); toChannel = out.getChannel();
	 * fromChannel.transferTo(0, fromChannel.size(), toChannel);
	 * 
	 * } catch (IOException e) { Log.e(TAG, "Error IOException: " +
	 * e.getMessage()); } catch (Exception e) { Log.e(TAG, "Error Exception: " +
	 * e.getMessage());
	 * 
	 * } finally { if (fromChannel != null) fromChannel.close(); if (toChannel
	 * != null) toChannel.close(); }
	 * 
	 * }
	 */

	/**
	 * call sevirce receipt
	 */
	private void callAsynCallServiceReceipt() {
		mModel = new Model(model, TaskType.TASK_GET_RECEIPT, null, this);
		if (Util.isNetworkActivated(Login.this)) {
			model.exeTask(null, mModel);
		} else {
			downloadfail();
			showToast(getString(R.string.no_connection));
		}
	}

	/**
	 * call sevirce trip by report ID
	 */
	private void callAsynCallServiceTrip() {
		mModel = new Model(model, TaskType.TASK_GET_TRIP, null, this);
		if (Util.isNetworkActivated(Login.this)) {
			model.exeTask(null, mModel);
		} else {
			downloadfail();
			showToast(getString(R.string.no_connection));
		}
	}

	/**
	 * call sevirce trip free
	 */
	private void callAsynCallServiceTripFree() {
		mModel = new Model(model, TaskType.TASK_GET_TRIP_FREE, null, this);
		if (Util.isNetworkActivated(Login.this)) {
			model.exeTask(null, mModel);
		} else {
			downloadfail();
			showToast(getString(R.string.no_connection));
		}
	}

	/**
	 * call sevirce report
	 */
	private void callAsynCallServiceReport(String limit, String offset) {
		mModel = new Model(model, TaskType.TASK_GET_REPORT, null, this);
		String[] mParams = { limit, offset };
		TaskParams params = new TaskParams(mParams);
		if (Util.isNetworkActivated(Login.this)) {
			model.exeTask(params, mModel);
		} else {
			downloadfail();
			showToast(getString(R.string.no_connection));
		}
	}

	/**
	 * call sevirce items
	 */

	private void callAsynCallServiceItems() {
		mModel = new Model(model, TaskType.TASK_GET_ITEMS, null, Login.this);
		if (Util.isNetworkActivated(Login.this)) {
			model.exeTask(params, mModel);
		} else {
			downloadfail();
			showToast(getString(R.string.no_connection));
		}
	}

	/**
	 * call sevirce trip items
	 */

	private void callAsynCallServiceTripItems() {
		mModel = new Model(model, TaskType.TASK_GET_TRIP_ITEMS, null,
				Login.this);
		if (Util.isNetworkActivated(Login.this)) {
			model.exeTask(params, mModel);
		} else {
			downloadfail();
			showToast(getString(R.string.no_connection));
		}
	}

	/**
	 * call sevirce receipt free
	 */

	private void callAsynCallServiceReceiptFree() {
		mModel = new Model(model, TaskType.TASK_GET_RECEIPT_FREE, null,
				Login.this);
		if (Util.isNetworkActivated(Login.this)) {
			model.exeTask(null, mModel);
		} else {
			downloadfail();
			showToast(getString(R.string.no_connection));
		}
	}

	/**
	 * call sevirce settings
	 */

	private void callAsynCallServiceSettings() {
		mModel = new Model(model, TaskType.TASK_SETTINGS, null, Login.this);
		if (Util.isNetworkActivated(Login.this)) {
			model.exeTask(null, mModel);
		} else {
			downloadfail();
			showToast(getString(R.string.no_connection));
		}
	}

	/**
	 * call sevirce category
	 */
	private void callAsynCallServiceCategory() {
		mModel = new Model(model, TaskType.TASK_GET_CATEGORYS, null, this);
		if (Util.isNetworkActivated(Login.this)) {
			model.exeTask(null, mModel);
		} else {
			downloadfail();
			showToast(getString(R.string.no_connection));
		}
	}

	private void callAsynCallServiceMerchant() {
		if (Util.isNetworkActivated(Login.this)) {
			Model mModel = new Model(model, TaskType.TASK_GET_MERCHANT, null,
					getBaseContext());
			model.exeTask(null, mModel);
		} else {
			showToast(getString(R.string.no_connection));
		}
	}

	private void callAsynCallServiceItemPeding() {
		if (Util.isNetworkActivated(Login.this)) {
			Model mModel = new Model(model, TaskType.TASK_GET_ITEM_PENDING,
					null, getBaseContext());
			model.exeTask(null, mModel);
		} else {
			showToast(getString(R.string.no_connection));
		}
	}

	private void callAsynCallServiceTripItemPeding() {
		if (Util.isNetworkActivated(Login.this)) {
			Model mModel = new Model(model, TaskType.TASK_GET_TRIPITEM_PENDING,
					null, getBaseContext());
			model.exeTask(null, mModel);
		} else {
			showToast(getString(R.string.no_connection));
		}
	}

}
